package com.rdc.jiajiadictionary.translate;

import android.content.Context;
import android.media.MediaPlayer;


import com.rdc.jiajiadictionary.base.BasePresenter;
import com.rdc.jiajiadictionary.bean.Word;
import com.rdc.jiajiadictionary.data.gettranslate.TranslateModel;
import com.rdc.jiajiadictionary.data.gettranslate.TranslateModelInterface;

import java.io.IOException;

public class TranslatePresenter implements BasePresenter {

    private Word mWord;
    private MediaPlayer mediaPlayer;
    private TranslateViewInterface mTranslateViewInterface;
    private TranslateModelInterface mTranslateModelInterface;
    @Override
    public void start() {

    }

    /**
     * 构造方法，传入一个view层接口，进行view层和presenter层的双向绑定，并创建model层对象的引用
     * @param translateViewInterface
     * @param context
     */
    public TranslatePresenter(TranslateViewInterface translateViewInterface, Context context){
        mTranslateViewInterface = translateViewInterface;
        mTranslateViewInterface.setPresenter(this);
        mTranslateModelInterface = new TranslateModel(context);
    }

    /**
     * 通过model层方法对view层传入的输入内容进行翻译，实现回调接口同时调用view层方法更新ui
     * @param text
     */
    public void translate(String text){
        mTranslateModelInterface.getTranslateData(text, new TranslateModel.GetDataCallBack() {
            @Override
            public void onComplete(Word word) {
                mTranslateViewInterface.setData(word);
                mWord = word;

            }
            @Override
            public void onDataNotAvailable() {

            }
        });
    }

    /**
     * 添加单词到生词本
     */
    public void addWordIntoNotebook(){
        mTranslateModelInterface.addWordIntoNotebookInDatabase(mWord);
    }

    /**
     * 从生词本中移除单词
     */
    public void removeWordFromNotebook(){
        mTranslateModelInterface.removeWordFromNotebookInDatabase(mWord);
    }

    /**
     * 播放单词发音
     * @param url
     */
    public void play(String url){

        if(null == mediaPlayer){
            mediaPlayer = new MediaPlayer();
            mTranslateViewInterface.toast("正在获取网络发音");
        }

        if(!mediaPlayer.isPlaying()){
            try {
                mediaPlayer.reset();
                mediaPlayer.setDataSource(url);
                mediaPlayer.prepare();
                mediaPlayer.start();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}
